﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using System.Xml.XLinq;
using Microsoft.Windows.Controls.Primitives;  


namespace WpfApplicationExperimental
{
    //Programmer me = new Programmer("Expert:)");public bool IsBurned(Programmer me){if(me.IsKeepCoding)return me.WillBurnMyMind();}

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Design3Experimental : Window, IListView
    {
        DocumentViewController documentController;
        
        [Obsolete ("this must be used in controller")]
        DataAccesLayer.Factory.IDataProvidersFactory DataLayer;  // new DataAccesLayer.EQualDataLayerFactory();

        MainViewPresenter mainViewController; 

        public Design3Experimental()
        {


            InitializeComponent();



            SetUpDataLayer();
            documentController = new DocumentViewController();


           
           mainViewController = new MainViewPresenter(new DataGridAdapter(MainGridView));

           // mainViewController.SetObjectProvider(new EmployeeObjectProvider());

            mainViewController.AddSecondaryPresenter (
                new DetailedControls.DetailsViewPresenter(documentDetailedControl1));

            mainViewController.AddSecondaryPresenter(
                new EmployeesListPresenter(new DataGridAdapter(Employeegrid)));

            mainViewController.AddSecondaryPresenter(
                new FormsListPresenter(new DataGridAdapter(dataGrid2)));
            
            mainViewController.OnSelectedItemChanged += new EventHandler(mainViewController_OnSelectedItemChanged);

            documentController.listView = this;

            this.documentDetailedControl1.OnCreated += new Action(documentDetailedControl1_OnCreated);

            SetUpTreeViewsContent();

            SetUpMenuCommands();

          //  this.ListDocuments();

            mainLabel.Content = "Eγγραφα";
            employeeLabel.Content = "Διανομή";
            formsLabel.Content = "Σχετιζόμενα Αρχεία 'Eντυπα";  
   
        }

        void mainViewController_OnSelectedItemChanged(object sender, EventArgs e)
        {
          //Note : fill this 
        }

        /// <summary>
        /// ok this is xml dependency injection in wpf .it is cool .if you change the xaml you get your own  
        /// datalayer [ IDataProvidersFactory ]without need to change code.got it ? i leave this virtual for the stupids 
        /// </summary>
        protected virtual  void SetUpDataLayer()
        {
            ObjectDataProvider dataLayerprovider =this.FindResource("DataLayer") as ObjectDataProvider;
     
            this.DataLayer = dataLayerprovider.Data as DataAccesLayer.Factory.IDataProvidersFactory;
        }

        private void SetUpMenuCommands()
        {
            MainManusCategoryGenerator.Commands.Add("Eγγραφα", new MainManusCategoryGenerator.MenuCommandItem("Eγγραφα", delegate()
            {
                this.ListDocuments();
                mainLabel.Content = "Eγγραφα";
            }));
            MainManusCategoryGenerator.Commands.Add("Eργαζομενοι", new MainManusCategoryGenerator.MenuCommandItem("Eργαζομενοι", delegate()
            {
                this.ListEmployees();
                mainLabel.Content = "Eργαζομενοι";
            }));
        }

        private void SetUpTreeViewsContent()
        {
            this.documentstreeview.ItemsSource = MainManusCategoryGenerator.GetMainMenuCategoryItems("Documents");
            this.failuresTreeView.ItemsSource = MainManusCategoryGenerator.GetMainMenuCategoryItems("failures");
            this.personeltreeview.ItemsSource = MainManusCategoryGenerator.GetMainMenuCategoryItems("Personel");
            this.projectsTreeView.ItemsSource = MainManusCategoryGenerator.GetMainMenuCategoryItems("projects");
            this.suppliesTreeView.ItemsSource = MainManusCategoryGenerator.GetMainMenuCategoryItems("projects");
            // replace this with command items wpf 
        }

        void documentDetailedControl1_OnCreated()
        {
            documentController.RequestNewDocumentCreation(documentDetailedControl1.SourceDocument as DataAccesLayer .Document );
        }

        private void TabItem_MouseDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void DataGrid_RowEditEnding(object sender, Microsoft.Windows.Controls.DataGridRowEditEndingEventArgs e)
        {
            
        }

        private void CustomerGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            mainViewController.MainGridSelectedItem = MainGridView.SelectedItem;

            return;

          /*  
            DataAccesLayer.Document doc = GetActiveDocument();

            if (doc != null)
            {
                SetSecondaryDocumentsDetailsControl(doc);
                SetSecondaryEmployeesDataGrid(doc);
                SetSecondaryFormsAndRecordsDataGrid(doc);
            }
           * */
        }

        /*
        private void SetSecondaryDocumentsDetailsControl(DataAccesLayer.Document doc)
        {
            this.documentDetailedControl1.Visibility = Visibility.Visible;
            this.documentDetailedControl1.DispalyDocumentDetails(doc);
        }

        private void SetSecondaryEmployeesDataGrid(DataAccesLayer.Document doc)
        {
            return;


            SetUpEmployeesColumns();


            DAOCollection<DataAccesLayer.Employee> employees = new DAOCollection<DataAccesLayer.Employee>( new DataAccesLayer.EmployeeDataAccesLayer().GetEmploeesDocumentNotification(doc.Id.ToString()));
            employees.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(employees_CollectionChanged);

            this.Employeegrid.ItemsSource =employees ;


        }

        private void SetUpEmployeesColumns()
        {
            this.Employeegrid.AutoGenerateColumns = false;
            Employeegrid.Columns.Clear();
            foreach (Microsoft.Windows.Controls.DataGridColumn col in MainDatagridColumnsGenerator.GetDataGridColumnsNewItemSecondaryGrid(typeof(DataAccesLayer.Employee).ToString()))
                this.Employeegrid.Columns.Add(col);
        }

        private void SetSecondaryFormsAndRecordsDataGrid(DataAccesLayer.Document doc)
        {
            this.dataGrid2.AutoGenerateColumns = false;
            dataGrid2.Columns.Clear();
            foreach (Microsoft.Windows.Controls.DataGridColumn col in MainDatagridColumnsGenerator.GetDataGridColumnsNewItemSecondaryGrid(typeof(DataAccesLayer.Form_Record).ToString()))
                this.dataGrid2.Columns.Add(col);
        DAOCollection <DataAccesLayer .Form_Record > forms = new DAOCollection<DataAccesLayer.Form_Record>(DataLayer.GetDocumentAccesLayer().GetDocumentFormsAndRecords(doc.Id));
            forms .CollectionChanged +=new System.Collections.Specialized.NotifyCollectionChangedEventHandler(forms_CollectionChanged);
            this.dataGrid2.ItemsSource = forms; 
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void forms_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                DataLayer.GetDocumentAccesLayer().RemoveFromRecordToDocument(GetActiveDocument(), e.OldItems  );
            }
        }
     */
        private DataAccesLayer.Document GetActiveDocument()
        {
            return (this.MainGridView.SelectedItem as DataAccesLayer.Document);
        }

    
        private void TabItem_MouseDown_1(object sender, MouseButtonEventArgs e)
        {

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            documentController.SubmitChanges();
        }

        #region IListView Members

        public void UpdateList()
        {

        }

        #endregion

        private void TabItem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

            System.Collections.IList docs = this.MainGridView.SelectedItems;

            foreach (DataAccesLayer.Document doc in docs)
                this.documentController.RequestDocumentDelete(doc);
        }

        private void Documentsgrid_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
        {

        }

        private void Documentsgrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {

        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            /*
             *Programmer me = new Programmer("Expert");if(me.IsKeepCoding){me.WillBurnMyMind();}
             */
        }

        private void DeleteEmployee(object sender, RoutedEventArgs e)
        {
            documentController.RequestAccosiationRemoveToDocument(((DataAccesLayer.Document)MainGridView.SelectedItem).Id, ((DataAccesLayer.Employee)Employeegrid.SelectedItem).id);
        }

        private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if ((this.documentstreeview.SelectedItem).ToString() == "Εγγραφα")
                MainManusCategoryGenerator.Commands["Eγγραφα"].Execute();
        }

        #region Listing Methodes
        protected  void ListDocuments()
        {

            this.MainGridView.Columns.Clear();


            foreach (DataGridColumn col in MainDatagridColumnsGenerator.GetDataGridColumns("Document"))
                this.MainGridView.Columns.Add(col);

            DAOCollection<DataAccesLayer.Document> documents = new DAOCollection<DataAccesLayer.Document>(DataLayer .GetDocumentAccesLayer().GetDocuments() );
            documents.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(documents_CollectionChanged);
            this.MainGridView.ItemsSource = documents;// DataAccesLayer.PresentationLayer.DocumentFilterdDataProvider.GetFilteredDocuments(documents as IEnumerable<DataAccesLayer.Document>);

        }

        void documents_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
               this.documentController.RequestDocumentDelete( e.OldItems );
            }
        }

        private void ListEmployees()
        {
            IEnumerable<DataAccesLayer.Employee> employees = DataLayer.GetEmployeeAccesLayer().GetEmployees();
            this.MainGridView.Columns.Clear();

            foreach (DataGridColumn col in MainDatagridColumnsGenerator.GetDataGridColumns("Employee"))
                this.MainGridView.Columns.Add(col);

  
            this.MainGridView.ItemsSource = employees;
        }

        void employees_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
               DataLayer .GetEmployeeAccesLayer (). RemoveEmployeeToBeNotified(GetActiveDocument(), e.OldItems);
            }

            //throw new ThisIsAGreatGroupException("Oxi allon codika");
        }
        #endregion

        private void personeltreeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if ((this.personeltreeview.SelectedItem).ToString() == "Εργαζομενοι")
                MainManusCategoryGenerator.Commands["Eργαζομενοι"].Execute();
        }

        private void MainGridView_KeyDown(object sender, KeyEventArgs e)
        {
   
        }

        private void MainGridView_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            
            if (MainGridView.SelectedItem is DataAccesLayer.Document)
            {
                DataAccesLayer.Document newDoc = GetActiveDocument();
                this.documentController.RequestNewDocumentCreation(newDoc);
            }
            if (MainGridView.SelectedItem is DataAccesLayer.Employee)
            {
                DataLayer.GetEmployeeAccesLayer().AddNewEmployee(MainGridView.SelectedItem as DataAccesLayer.Employee);
            }

        }

        private void MainGridView_StylusButtonDown(object sender, StylusButtonEventArgs e)
        {

        }

        #region IListView Members

        public void ErrorOnNewAddition(object document)
        {
            throw new NotImplementedException();
        }

        #endregion

        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {

        }

        private void MenuItem_Click_4(object sender, RoutedEventArgs e)
        {
  
        }

        private void MainGridView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
           
        }

        private void MainGridView_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            ColumnSelectionWindow win = new ColumnSelectionWindow();
            if (this.MainGridView.SelectedItem == null) return;
            win.CreateColumns(this.MainGridView.SelectedItem.GetType());
            if (win.ShowDialog() == true)
            {

            }

            List<string> list = win.columnsSelected;
            if (list.Count == 0) return;
            this.MainGridView.Columns.Clear();

            foreach (DataGridColumn col in MainDatagridColumnsGenerator.GetDataGridColumnsFiltered(MainGridView.SelectedItem.GetType().ToString(), list))
                this.MainGridView.Columns.Add(col);
        }

        private void dataGrid2_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            //new DataAccesLayer.DocumentDataAccesLayer().AddNewDocumentVersion();
            DataLayer.GetDocumentAccesLayer().AddNewFromRecordToDocument(e.Row.Item as DataAccesLayer.Form ,GetActiveDocument () );
        }



        private void Employeegrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        private void Employeegrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            if (GetActiveDocument () != null && (this.Employeegrid.SelectedItem as DataAccesLayer.Employee) != null)
               DataLayer.GetEmployeeAccesLayer (). AddEmployeeToBeNotified(GetActiveDocument ().Id , (this.Employeegrid.SelectedItem as DataAccesLayer.Employee).id);
        }


    }

                              

}
